package com.neuedu.web.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 金山
 * 项目：javaweb
 * site: https://blog.fulfill.com.cn
 * 描述
 * @data 2024/11/1511:49
 */
// @WebFilter(urlPatterns = "/*")
// @WebFilter(value = "/*")
@WebFilter( "/*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CorsFilter.init");
    }

    /**
     * 执行的 过滤 核心代码
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        System.out.println("request.getMethod() = " + request.getMethod());


        // System.out.println("跨域的 设置  Filter");
        // 解决跨域的问题
        // response.setHeader("Access-Control-Allow-Origin", "http://localhost");

        //开发的时候可以使用
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        //允许跨域的时候 使用 cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST");

        if("OPTIONS".equals(request.getMethod())){

            response.setHeader("Access-Control-Allow-Headers", "content-type");
            return;
        }


        //Filter 链 方形
        filterChain.doFilter(servletRequest,servletResponse);

    }

    @Override
    public void destroy() {
        System.out.println("CorsFilter.destroy");
    }
}
